package com.qiuzhao.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.util.UUID;

public class QiniuOssUtil {

    static final String ACCESS_KEY = "T4L4ZFGm06P-uDvWvMh_2MrFJ7dZ1t1rFRpscUL1";
    static final String SECRET_KEY = "_peaTz9r4RTRtBu8EYd83JXw4hLJN8_CeHFl7bFW";
    private static final String BUCKET = "audio-qiuzhao";
    private static final String DOMAIN = "http://t310jkb8x.hb-bkt.clouddn.com"; // 七牛空间绑定的域名

    private static final UploadManager uploadManager;

    static {
        // 设置七牛云区域
        Configuration cfg = new Configuration(Region.region1()); // 华北 z1
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2; // 分片上传 V2
        uploadManager = new UploadManager(cfg);
    }

    /**
     * 上传字节数组到七牛云 OSS，存储为 MP3
     *
     * @param audioBytes 音频字节数组
     * @return 文件 URL
     * @throws QiniuException 上传失败会抛出异常
     */
    public static String uploadAudio(byte[] audioBytes) throws QiniuException {
        // 随机生成文件名，确保唯一性
        String fileName = UUID.randomUUID() + ".webm";

        // 构建上传凭证
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);

        // 上传
        Response response = uploadManager.put(audioBytes, fileName, upToken);
        // 解析结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        return DOMAIN + "/" + putRet.key;
    }
}
